package com.sdksoft.readcard

import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.RadioGroup
import com.csht.constants.Constant
import com.csht.enums.ReadCardType
import com.csht.enums.StatusCode
import com.csht.listener.InitListener
import com.csht.listener.ReadCardListener
import com.sdksoft.readcard.databinding.LayoutM1CardBinding
import com.csht.utils.BytesUtils
import com.csht.utils.DevicesUtils
import com.csht.utils.HHTipUtils
import com.csht.utils.NfcUtils


class UsbM1Activity : BaseInitActivity(), InitListener, ReadCardListener, RadioGroup.OnCheckedChangeListener {

    private var initSuccess = false
    lateinit var layoutM1CardBinding: LayoutM1CardBinding
    private val mHandler: Handler = Handler(Looper.getMainLooper())
    //1.声明一个nfc的Adapter
    private lateinit var nfcUtils: NfcUtils
    private var mIntent: Intent? = null

    // 扇区编号    第0扇区的块0（即绝对地址0块），它用于存放厂商代码，已经固化，不可更改。
    private var options = arrayOf("00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F")
    private var optionsKuai = arrayOf("00", "01", "02", "03") // 每个扇区包含4个块，编号从0到3。块3用于存放密码和控制权限‌。
    private var shanquNum = options[0]
    private var kuaiNum = optionsKuai[0]
    private var mReadCardType = ReadCardType.USB
    override fun initView() {
        super.initView()
        setTitleText("M1读写卡")
        layoutM1CardBinding = LayoutM1CardBinding.inflate(layoutInflater)
        baseActivityBinding.llContent.addView(layoutM1CardBinding.root)
        nfcUtils = NfcUtils(this,  this.javaClass)

        layoutM1CardBinding.apply {
            rgType.setOnCheckedChangeListener(this@UsbM1Activity)
            rbUsb.isChecked = true
            btnReset.setOnClickListener {
                if (!initSuccess) {
                    HHTipUtils.getInstance().showToast(baseContext, "未初始化成功")
                    return@setOnClickListener
                }
                val time = etResetTime.text.toString().toLongOrNull()
                if (time == null) { // 正在复位
                    HHTipUtils.getInstance().showToast(baseContext, "请输入有效复位时间")
                    return@setOnClickListener
                }
                readSettingBuilder.buildReBootGatTime(time)
            }
            // 读取M1卡信息
            btnReadM1.setOnClickListener {
                if (!initSuccess) {
                    HHTipUtils.getInstance().showToast(baseContext, "未初始化成功")
                    return@setOnClickListener
                }
                val key = etKey.text.toString().replace(" ", "")
                if (TextUtils.isEmpty(key) || key.length != 12) {
                    HHTipUtils.getInstance().showToast(baseContext, "请输入正确的扇区密钥")
                    return@setOnClickListener
                }

                try {
                    val bytes = BytesUtils.hexStringToBytes(shanquNum + "00").plus(BytesUtils.hexStringToBytes(key)).plus(BytesUtils.hexStringToBytes(kuaiNum))
                    readCardManager.M1Card(1, bytes, this@UsbM1Activity, mIntent)
                } catch (e: Exception) {
                    HHTipUtils.getInstance().showToast(baseContext, "发送异常" + e.message)
                }
            }
            btnWr.setOnClickListener {
                if (!initSuccess) {
                    HHTipUtils.getInstance().showToast(baseContext, "未初始化成功")
                    return@setOnClickListener
                }
                val key = etKey.text.toString().replace(" ", "")
                if (TextUtils.isEmpty(key) || key.length != 12) {
                    HHTipUtils.getInstance().showToast(baseContext, "请输入正确的扇区密钥")
                    return@setOnClickListener
                }
                val hexContent = etContent.text.toString().replace(" ", "")
                if (TextUtils.isEmpty(hexContent)) {
                    HHTipUtils.getInstance().showToast(baseContext, "请输入写入内容")
                    return@setOnClickListener
                }
                try {
                    val bytes = BytesUtils.hexStringToBytes(shanquNum + "00").plus(BytesUtils.hexStringToBytes(key)).plus(BytesUtils.hexStringToBytes(kuaiNum))
                    val content = hexContent.toByteArray(Charsets.UTF_8)
                    if (content.size > 16) {
                        HHTipUtils.getInstance().showToast(baseContext, "单块最大只能写入16字节")
                    } else {
                        readCardManager.M1Card(2, bytes.plus(content), this@UsbM1Activity, mIntent)
                    }
                } catch (e: Exception) {
                    HHTipUtils.getInstance().showToast(baseContext, "发送异常" + e.message)
                }
            }
            btnPsw.setOnClickListener {
                if (!initSuccess) {
                    HHTipUtils.getInstance().showToast(baseContext, "未初始化成功")
                    return@setOnClickListener
                }
                val key = etKey.text.toString().replace(" ", "")
                if (TextUtils.isEmpty(key) || key.length != 12) {
                    HHTipUtils.getInstance().showToast(baseContext, "请输入正确的扇区密钥")
                    return@setOnClickListener
                }
                val newKey = etNewKey.text.toString().replace(" ", "")
                if (TextUtils.isEmpty(newKey) || newKey.length != 12) {
                    HHTipUtils.getInstance().showToast(baseContext, "请输入新密钥")
                    return@setOnClickListener
                }
                try {
                    val bytes = BytesUtils.hexStringToBytes(shanquNum + "00").plus(BytesUtils.hexStringToBytes(key)).plus(BytesUtils.hexStringToBytes(newKey))
                    readCardManager.M1Card(3, bytes, this@UsbM1Activity, mIntent)
                } catch (e: Exception) {
                    HHTipUtils.getInstance().showToast(baseContext, "发送异常" + e.message)
                }
            }
            tvLog.setOnLongClickListener {
                tvLog.text = ""
                return@setOnLongClickListener false
            }

            // 创建ArrayAdapter
            val adapter: ArrayAdapter<String> = ArrayAdapter<String>(this@UsbM1Activity, android.R.layout.simple_spinner_item, options)
            spShanqu.adapter = adapter
            val adapterKuai: ArrayAdapter<String> = ArrayAdapter<String>(this@UsbM1Activity, android.R.layout.simple_spinner_item, optionsKuai)
            spKuai.adapter = adapterKuai
            spShanqu.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    shanquNum = options[position]
                    HHTipUtils.getInstance().showToast(baseContext, "选择扇区编号：$shanquNum")
                    appendLog("\n选择扇区编号：$shanquNum")
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                }
            }
            spKuai.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    kuaiNum = optionsKuai[position]
                    HHTipUtils.getInstance().showToast(baseContext, "选择块号：$kuaiNum")
                    appendLog("\n选择块号：$kuaiNum")
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                }
            }
        }
    }
    override fun onStart() {
        super.onStart()
        Log.d("readcard", "onStart")
        nfcUtils.nfcInit( this, this.javaClass)
    }

    override fun onResume() {
        super.onResume()
        Log.d("readcard", "onResume")
        //设置处理优于所有其他NFC的处理
        nfcUtils.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        Log.d("readcard", "onPause")
        //恢复默认状态
        nfcUtils.onPause(this)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        if (initSuccess.not()) {
            HHTipUtils.getInstance().showToast(this, "没有初始化成功")
            return
        }
        HHTipUtils.getInstance().showToast(baseContext, "NFC已检测到卡片")
        mIntent = intent
    }
    override fun onResponse(code: Int, msg: String) {
        mHandler.post {
            baseActivityBinding.tvVersion.apply {
                text =
                    "v${BuildConfig.VERSION_NAME}\n${DevicesUtils.getDeviceId(baseContext)}"
                setTextIsSelectable(true)
                append("\n读卡器版本：${readCardManager.readFirmwareVersion()},序列号：${Constant.hardwareNumber}")
            }
            when (code) {
                StatusCode.ININ_OK.code -> {
                    initSuccess = true
                    appendLog("\n 初始化成功")
                }
                StatusCode.ININ_ING.code -> {
                    initSuccess = false
                    appendLog("\n 初始化中...")
                }
                else -> {
                    initSuccess = false
                    appendLog("\n 初始化失败")
                }
            }
        }
    }
    override fun onReadCardState(type: Int, msg: String?) {
        if (type == StatusCode.READCARD_FAILE.code) {
            HHTipUtils.getInstance().dismissProgressDialog()
            HHTipUtils.getInstance().showToast(this, "type:$type\n$msg")
        } else if (type == StatusCode.READCARD_SUCCESS.code) {
            HHTipUtils.getInstance().dismissProgressDialog()
            HHTipUtils.getInstance().showToast(this, "type:$type\n$msg")
        } else if (type == StatusCode.FIND_CARD_SUCCESS.code) {
            if (!HHTipUtils.getInstance().progressDialogIsShowing()) {
                HHTipUtils.getInstance().showProgressDialog(this, "正在读取,请勿移动")
            }
        }
        appendLog("\n----------------------------\nstatus: $type  ，msg:$msg")
    }

    override fun onResultM1Data(data: ByteArray?) {
        super.onResultM1Data(data)
        HHTipUtils.getInstance().dismissProgressDialog()
        data?.let {
            appendLog("\n----------------------------\nM1卡: \n${String(data, Charsets.UTF_8)}")
        }
    }

    fun appendLog(log: String) {
        layoutM1CardBinding.apply {
            tvLog.append(log)
            mHandler.postDelayed({ logScroll.fullScroll(View.FOCUS_DOWN) }, 200)
        }
    }

    override fun onDestroy() {
        readCardManager.readCardStop()
        readCardManager.readCardReleaseDestory()
        super.onDestroy()
    }

    override fun onCheckedChanged(group: RadioGroup, checkedId: Int) {
        when (checkedId) {
            R.id.rb_usb -> {
                mReadCardType = ReadCardType.USB
            }
            R.id.rb_nfc -> {
                mReadCardType = ReadCardType.NFC_M1
            }
        }
        readCardManager.readCardStop()
        readCardManager.readCardReleaseDestory()
        readSettingBuilder.buildReadCardType(mReadCardType)
        readCardManager.readCardInit(this@UsbM1Activity)
    }
}